//
//  EDSRecordVideoViewController.m
//  DrivieSchoolStudents
//
//  Created by TangBin on 2019/5/21.
//  Copyright © 2019 班文政. All rights reserved.
//

#import "EDSRecordVideoViewController.h"
#import "ALiVideoRecorder.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>
#import <CoreMotion/CoreMotion.h>
#import "HProgressView.h" // 长按录制视频动画
#import "HAVPlayer.h" // 播放录制的视频
#import "EDSImageVideoModel.h"


@interface EDSRecordVideoViewController () <ALiVideoRecordDelegate>

@property (nonatomic, strong) HAVPlayer *player;

/**
 录视频
 */
@property (nonatomic, strong) ALiVideoRecorder *recorder;

/**
 最后的方向
 */
@property (nonatomic, assign) UIInterfaceOrientation orientationLast;

/**
 用来监听来电的
 */
@property (nonatomic, strong) CTCallCenter *callCenter;

/**
 是否正在有来电
 */
@property (nonatomic, assign) BOOL hasIncomingCall;

/**
 加速度和陀螺仪
 */
@property (nonatomic, strong) CMMotionManager *motionManager;

/**
 切换相机
 */
@property (nonatomic, strong) UIButton *btnChangeCamera;

/**
 曝光，焦点
 */
@property (nonatomic, strong) UIImageView *focusImageView;
@property (nonatomic, assign) BOOL isFocus; ///< NO 表示没有显示，YES表示显示

@property (nonatomic, strong) UIButton *btnAfresh; ///< 重新录制视频/拍照
@property (nonatomic, strong) UIButton *btnEnsure; ///< 应用这个视频
@property (nonatomic, strong) HProgressView *progressView; ///< 长按视频动画
@property (nonatomic, assign) BOOL isProgressSecond; ///< 是否赋值过
@property (nonatomic, strong) UIImageView *recordImageView; ///< 录制视频看到的图片

@property (nonatomic, strong) UIButton *btnBack; ///< 返回按钮

@property (nonatomic, assign) BOOL isVideo; ///< 是否是视频录制（其实都是视频录制）
@property (nonatomic, strong) UIImageView *takeImageView; ///< 图片的话，就会显示

@property (nonatomic, strong) UIImage *destImage; ///< 完成的图片
@property (nonatomic, strong) NSString *destVideoUrl; ///< 视频地址

@property (nonatomic, assign) NSInteger recordSeconds; ///< 会用来做递减的

/**
 提示“轻触拍照，按住摄像”
 */
@property (nonatomic, strong) UILabel *tipLabel;


/**
 录制视频
 */
- (void)initWithRecorder;

/**
 初始化切换相机按钮
 */
- (void)initWithBtnChangeCamera;

@end

@implementation EDSRecordVideoViewController

- (void)dealloc
{
    NSLog(@"%s", __func__);
    
}

- (void)initWithVar
{
    [super initWithVar];
    if (self.recordVideoSeconds == 0)
    {
        self.recordVideoSeconds = kRECORD_VIDEO_TIME;
    }
    
    // 裁剪视频完成后，收到通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cropVideoFinished:) name:kVIDEO_CLIP_FINISHED_NOTI object:nil];
    
}

- (void)initWithNavBar
{
    [super initWithNavBar];
    
}

- (void)initWithSubView
{
    [super initWithSubView];
    
    // 录制视频
    [self initWithRecorder];
    
    [self initWithBtnChangeCamera];
    
    [self.view addSubview:self.focusImageView];
    
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapScreen:)];
    [self.view addGestureRecognizer:tapGesture];
    
    [self.view addSubview:self.btnAfresh];
    [self.view addSubview:self.btnEnsure];
    [self.view addSubview:self.recordImageView];
    [self.view addSubview:self.progressView];
    self.btnAfresh.hidden = YES;
    self.btnEnsure.hidden = YES;
    self.progressView.hidden = YES;
    [self.view addSubview:self.btnBack];
    [self.view addSubview:self.tipLabel];
    [self hiddenTipLabel];
//    @weakify(self);
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        @strongify(self);
//        self.tipLabel.hidden = YES;
//    });
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    // 注册进入后台的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackgroundMode:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    // 初始化监听来电
    [self detectIncomingCall];
    
    if ([self.motionManager isAccelerometerAvailable])
    {// 加速度可用
        // 手机方向改变
        [self orientationChange];
    }
    
    // 启动录制功能
    [self.recorder openPreview];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // 启动录制功能
//    [self.recorder openPreview];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.motionManager stopAccelerometerUpdates];
    self.motionManager = nil;
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    // 关闭预览
    [self.recorder closePreview];
    [super viewDidDisappear:animated];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}


- (void)clickedBack:(id)sender
{
    if (self.recorder.isCapturing)
    {
        //正在录制 停止录制删除缓存
        [self.recorder unloadInputOrOutputDevice];
        [self.recorder cleanCache];
    }
    
    [super clickedBack:sender];
}

#pragma mark - 初始化
/**
 录制视频
 */
- (void)initWithRecorder
{
    if (!_recorder)
    {
        _recorder = [[ALiVideoRecorder alloc] init];
        _recorder.maxVideoDuration = 3600;
        _recorder.delegate = self;
        _recorder.previewLayer.frame = self.view.bounds;
        [self.view.layer insertSublayer:_recorder.previewLayer atIndex:0];
    }
}

- (void)initWithBtnChangeCamera
{
    if (!_btnChangeCamera)
    {
        // btn_video_flip_camera
        // (kNavigationH - y)
        int y = 44;
        CGRect frame = CGRectMake(0, (NAVBAR_HEIGHT_STATUS - y) + (y-38) * 0.5, 38, 38);
        _btnChangeCamera = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnChangeCamera setImage:[UIImage imageNamed:@"btn_video_flip_camera"] forState:UIControlStateNormal];
        _btnChangeCamera.frame = frame;
        _btnChangeCamera.right = kScreenWidth - 5;
        [_btnChangeCamera addTarget:self action:@selector(changeCamera:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_btnChangeCamera];
    }
}

/**
 裁剪视频完成后，收到通知

 @param noti noti description
 */
- (void)cropVideoFinished:(NSNotification *)noti
{
    debugLog(@"录制视图完成通知");
    dispatch_async(dispatch_get_main_queue(), ^{
        EDSImageVideoModel *model = (EDSImageVideoModel *)[noti object];
        if (self.completionBlock)
        {
            self.completionBlock(model);
        }
        [self clickedBack:nil];
    });
}

#pragma mark - setter getter
- (CMMotionManager *)motionManager
{
    if (!_motionManager)
    {
        _motionManager = [[CMMotionManager alloc] init];
        _motionManager.accelerometerUpdateInterval = 1.0f/15.0;
    }
    return _motionManager;
}

- (UIImageView *)focusImageView
{
    if (!_focusImageView)
    {
        CGRect frame = CGRectMake(44, 126, 60, 60);
        _focusImageView = [[UIImageView alloc] initWithFrame:frame];
        _focusImageView.image = [UIImage imageNamed:@"ic_camera_focu"];
        _focusImageView.alpha = 0;
    }
    return _focusImageView;
}

/**
 重置，就是取消这次录的视频

 @return return value description
 */
- (UIButton *)btnAfresh
{
    if (!_btnAfresh)
    {
        int y = 170 + IPHONEX_BOTTOM_SPACE;
        UIImage *image = [UIImage imageNamed:@"btn_video_cancel"];
        CGRect frame = CGRectMake(0, kScreenHeight - y, 70, 70);
        _btnAfresh = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnAfresh.frame = frame;
        _btnAfresh.centerX = kScreenWidth * 0.5;
        [_btnAfresh setImage:image forState:UIControlStateNormal];
        [self.view addSubview:_btnAfresh];
        
        @weakify(self);
        [[_btnAfresh rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self recovertLayout];// 重置
        }];
        
    }
    return _btnAfresh;
}

- (UIButton *)btnEnsure
{
    if (!_btnEnsure)
    {
        CGRect frame = _btnAfresh.frame;
        UIImage *image = [UIImage imageNamed:@"btn_video_confirm"];
        _btnEnsure = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnEnsure.frame = frame;
        [_btnEnsure setImage:image forState:UIControlStateNormal];
        
        @weakify(self);
        [[_btnEnsure rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            EDSImageVideoModel *model = [EDSImageVideoModel new];
            model.srcImage = self.destImage;
//            NSLog(@"isVideo=%d", self.isVideo);
            if (self.isVideo)
            {// 视频
                model.videoOrAudioUrl = [NSURL fileURLWithPath:self.destVideoUrl];
                model.fileSize = [self.recorder getFileSize:self.destVideoUrl];
                model.seconds = [self.recorder getVideoLength:[NSURL fileURLWithPath:self.destVideoUrl]];
                model.type = 1;
                
                // 视频要先进入编辑界面
//                UIViewController *videoPreviewVC = [[TYZRouter sharedInstance] getVideoPreviewVC:@{@"videoUrl":model.videoOrAudioUrl, @"isShowCrop":@(YES), @"model":model}];
//                [TYZJumpVCManager pushBaseVC:self pushVC:videoPreviewVC];
                return;
            }
            else
            {// 图片
                model.type = 0;
            }
            if (self.completionBlock)
            {
                self.completionBlock(model);
            }
            [self clickedBack:nil];
        }];
    }
    return _btnEnsure;
}

- (HProgressView *)progressView
{
    if (!_progressView)
    {
        CGRect frame = CGRectMake(0, 0, 87, 87);
        _progressView = [[HProgressView alloc] initWithFrame:frame];
        _progressView.backgroundColor = [UIColor colorWithHexString:@"#CFCAC6"];
        _progressView.center = self.btnAfresh.center;
        _progressView.layer.cornerRadius = _progressView.width * 0.5;
        _progressView.layer.masksToBounds = YES;
    }
    return _progressView;
}

- (UIImageView *)recordImageView
{
    if (!_recordImageView)
    {
        CGRect frame = CGRectMake(0.0f, 0.0f, 67, 67);
        _recordImageView = [[UIImageView alloc] initWithFrame:frame];
        _recordImageView.image = [UIImage imageNamed:@"sc_btn_take"];
        _recordImageView.center = self.btnAfresh.center;
        _recordImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
        [_recordImageView addGestureRecognizer:tap];
        
        if (self.type == 1)
        {
            UILongPressGestureRecognizer *longPressTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];
            [_recordImageView addGestureRecognizer:longPressTap];
        }
    }
    return _recordImageView;
}

- (UIButton *)btnBack
{
    if (!_btnBack)
    {
        // btn_recvideo_back
        CGRect frame = CGRectMake(0, 0, 40, 40);
        _btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnBack.frame = frame;
        [_btnBack setImage:[UIImage imageNamed:@"btn_recvideo_back"] forState:UIControlStateNormal];
        _btnBack.centerY = _btnAfresh.centerY;
        _btnBack.right = _btnAfresh.left - 40;
        
        @weakify(self);
        [[_btnBack rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self clickedBack:nil];
        }];
    }
    return _btnBack;
}

- (UILabel *)tipLabel
{
    if (!_tipLabel)
    {
        CGRect frame = CGRectMake(30, 0, kScreenWidth - 60, 20);
        _tipLabel = [[UILabel alloc] initWithFrame:frame];
        if (self.type == 1)
        {
            _tipLabel.text = @"轻触拍照，按住摄像";
        }
        else
        {
            _tipLabel.text = @"轻触拍照";
        }
        _tipLabel.centerX = kScreenWidth * 0.5;
        _tipLabel.textColor = [UIColor whiteColor];
        _tipLabel.font = [UIFont systemFontOfSize:13];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.bottom = self.btnAfresh.top - 30;
    }
    return _tipLabel;
}

#pragma mark - UITapGestureRecognizer
- (void)tapGesture:(UITapGestureRecognizer *)tap
{
    self.isVideo = NO;
//    NSLog(@"点击");
    [self startRecord];
    [self performSelector:@selector(stopRecord) withObject:nil afterDelay:0.3];
}

- (void)longPressGesture:(UILongPressGestureRecognizer *)tap
{
//    NSLog(@"state=%d", tap.state);
    
    
    
    if (tap.state == UIGestureRecognizerStateBegan)
    {
        if (self.isLastTimeImage)
        {
            return;
        }
        self.isVideo = YES;
        
//        NSLog(@"长按开始");
        [self startRecord];
    }
    else if (tap.state == UIGestureRecognizerStateEnded)
    {
//        NSLog(@"长按结束");
        if (self.isLastTimeImage)
        {
            [self tapGesture:nil]; // 当成拍照
            return;
        }
        [self stopRecord];
    }
    else if (tap.state == UIGestureRecognizerStateCancelled)
    {
//        NSLog(@"长按取消");
    }
    else if (tap.state == UIGestureRecognizerStateFailed)
    {
//        NSLog(@"faile");
    }
    
}

//@property (nonatomic, strong) UIButton *btnAfresh; ///< 重新录制视频/拍照
//@property (nonatomic, strong) UIButton *btnEnsure; ///< 应用这个视频
//@property (nonatomic, strong) HProgressView *progressView; ///< 长按视频动画
//@property (nonatomic, strong) UIImageView *recordImageView; ///< 录制视频看到的图片

#pragma mark - private methods

/**
 显示4秒后隐藏
 */
- (void)hiddenTipLabel
{
    @weakify(self);
    if (self.isLastTimeImage)
    {
        self.tipLabel.hidden = YES;
        return;
    }
    self.tipLabel.hidden = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @strongify(self);
        self.tipLabel.hidden = YES;
        if (self.type == 1)
        {
            self.tipLabel.text = @"轻触拍照，按住摄像";
        }
        else
        {
            self.tipLabel.text = @"轻触拍照";
        }
    });
}


/**
 开始录制
 */
- (void)startRecord
{
    self.recordSeconds = self.recordVideoSeconds;
    if (!self.recorder.isCapturing)
    {
        self.destVideoUrl = nil;
        self.destImage = nil;
        [self.recorder startRecording];
        [self configVideoOutputOrientation];
        self.isProgressSecond = NO;
        [self performSelector:@selector(onStartTranscribe) withObject:nil afterDelay:1];
    }
    else
    {
        [self stopRecord];
    }
}

/**
 停止录制
 */
- (void)stopRecord
{
    if (!self.recorder.isCapturing)
    {
        return;
    }
    @weakify(self);
    [self.recorder stopRecordingSavePhotoAlbum:NO handler:^(UIImage *movieImage) {
        @strongify(self);
//        NSLog(@"videoPath=%@", self.recorder.videoPath);
        NSURL *url = [NSURL fileURLWithPath:self.recorder.videoPath];
        
        CGFloat duration = [self.recorder getVideoLength:url];
        [self.recorder movieToImageHandler:^(UIImage *movieImage) {
           // 得到图片
            self.destImage = movieImage;
            if (self.isVideo)
            {// 视频
                if (duration <= 3)
                {// 录视频太短-- 录制时间过短
                    self.tipLabel.text = @"录制时间过短";
                    [self hiddenTipLabel];
                    [self.recorder cleanCache]; // 删除当前的视频
                    [self.progressView clearProgress];
                    return;
                }
                self.destVideoUrl = self.recorder.videoPath;
                if (!self.player)
                {
                    self.player = [[HAVPlayer alloc] initWithFrame:self.view.bounds withShowInView:self.view url:url];
                }
                else
                {
                    self.player.videoUrl = url;
                    self.player.hidden = NO;
                }
            }
            else
            {// 图片
                [self showTakeImageView:movieImage];
                [self.recorder cleanCache]; // 删除当前的视频
            }
//            NSLog(@"thred=%@", [NSThread currentThread]);
            [self changeLayout];
        }];
    }];
//    [self changeLayout];
}

/**
 倒计时
 */
- (void)onStartTranscribe
{
    if (self.recorder.isCapturing && self.isVideo)
    {// 表示正在录制
        --self.recordSeconds;
        if (self.recordSeconds > 0)
        {
            if (!self.isProgressSecond)
            {
                self.progressView.timeMax = self.recordSeconds;
                self.isProgressSecond = YES;
            }
            
            [self performSelector:@selector(onStartTranscribe) withObject:nil afterDelay:1];
        }
        else
        {
            [self stopRecord];
        }
    }
}

/**
 显示图片
 */
- (void)showTakeImageView:(UIImage *)image
{
    if (!_takeImageView)
    {
        _takeImageView = [[UIImageView alloc] initWithFrame:self.view.frame];
        [self.view addSubview:_takeImageView];
    }
    _takeImageView.hidden = NO;
    _takeImageView.image = image;
    
}

/**
 切换相机

 @param sender sender description
 */
- (void)changeCamera:(id)sender
{
    [self.recorder switchCamera];
}

/**
 监听来电
 当有电话进来的时候，停止录制视频
 */
- (void)detectIncomingCall
{
    @weakify(self);
    if (!_callCenter)
    {
        _callCenter = [[CTCallCenter alloc] init];
        _callCenter.callEventHandler = ^(CTCall * call) {
            @strongify(self);
            if ([call.callState isEqualToString:CTCallStateIncoming])
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.hasIncomingCall = YES;
                    [self stopRecord];
                });
            }
            else
            {
                self.hasIncomingCall = NO;
            }
        };
        
        
    }
}

/**
 改变方向 重力，加速剂等，改变方向
 */
- (void)orientationChange
{
    @weakify(self);
    [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
        
        @strongify(self);
        CMAcceleration acceleration = accelerometerData.acceleration;
        UIInterfaceOrientation orientationNew;
        if (acceleration.x >= 0.75)
        {
            orientationNew = UIInterfaceOrientationLandscapeLeft;
        }
        else if (acceleration.x <= -0.75)
        {
            orientationNew = UIInterfaceOrientationLandscapeRight;
        }
        else if (acceleration.y <= -0.75)
        {
            orientationNew = UIInterfaceOrientationPortrait;
        }
        else if (acceleration.y >= 0.75)
        {
            orientationNew = UIInterfaceOrientationPortraitUpsideDown;
            return ;
        }
        else
        {
            // Consider same as last time
            return;
        }
        
        
        if (!self.recorder.isCapturing)
        {
            if (orientationNew == self.orientationLast)
            {
                return;
            }
//            NSLog(@"更新");
            self.orientationLast = orientationNew;
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                if (orientationNew == self.orientationLast)
//                {
//                    return;
//                }
//                //     [weakSelf configView:orientationNew];
//                self.orientationLast = orientationNew;
//            });
        }
        
    }];
}

/**
 录制视频的时候调用，用来改变方向
 */
- (void)configVideoOutputOrientation
{
//    NSLog(@"orientationLast=%d", self.orientationLast);
    switch (self.orientationLast)
    {
        case UIInterfaceOrientationPortrait:
        {
            self.recorder.recordOrientation = EArtRecordOrientationPortrait;
            [self.recorder adjustRecorderOrientation:AVCaptureVideoOrientationPortrait];
        } break;
        case UIInterfaceOrientationLandscapeRight:
        {
            self.recorder.recordOrientation = EArtRecordOrientationLandscapeRight;
            [self.recorder adjustRecorderOrientation:AVCaptureVideoOrientationLandscapeRight];
        } break;
        case UIInterfaceOrientationLandscapeLeft:
        {
            self.recorder.recordOrientation = EArtRecordOrientationLandscapeLeft;
            [self.recorder adjustRecorderOrientation:AVCaptureVideoOrientationLandscapeLeft];
        } break;
        default:
            NSLog(@"不支持的录制方向");
            break;
    }
}

/**
 *  设置聚焦光标位置
 *
 *  @param point 光标位置
 */
-(void)setFocusCursorWithPoint:(CGPoint)point
{
    if (!self.isFocus)
    {
        self.isFocus = YES;
        self.focusImageView.center = point;
        self.focusImageView.transform = CGAffineTransformMakeScale(1.25, 1.25);
        self.focusImageView.alpha = 1.0;
        [UIView animateWithDuration:0.5 animations:^{
            self.focusImageView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [self performSelector:@selector(onHiddenFocusCurSorAction) withObject:nil afterDelay:0.5];
        }];
    }
}

- (void)onHiddenFocusCurSorAction
{
    self.focusImageView.alpha = 0;
    self.isFocus = NO;
}

/**
 拍摄完成后调用，用来显示完成后的视图
 */
- (void)changeLayout
{
    self.recordImageView.hidden = YES;
    self.btnChangeCamera.hidden = YES;
    self.btnAfresh.hidden = NO;
    self.btnEnsure.hidden = NO;
    self.btnBack.hidden = YES;
    [self.view bringSubviewToFront:self.btnAfresh];
    [self.view bringSubviewToFront:self.btnEnsure];
    if (self.isVideo)
    {
        [self.progressView clearProgress];
    }
    [UIView animateWithDuration:0.25 animations:^{
        self.btnAfresh.centerX = (kScreenWidth / 2/ 2);
        self.btnEnsure.centerX = kScreenWidth * 0.5 + (kScreenWidth / 2/ 2);
    }];
}

/**
 重新拍摄时调用
 */
- (void)recovertLayout
{
    if (self.destVideoUrl)
    {
        [[NSFileManager defaultManager] removeItemAtPath:self.destVideoUrl error:nil];
    }
    self.recordSeconds = self.recordVideoSeconds;
    self.destImage = nil;
    self.destVideoUrl = nil;
    if (self.isVideo)
    {
        self.isVideo = NO;
        [self.player stopPlayer];
        self.player.hidden = YES;
    }
    [self.recorder openPreview];
    if (!self.takeImageView.hidden)
    {
        self.takeImageView.hidden = YES;
    }
    self.recordImageView.hidden = NO;
    self.btnChangeCamera.hidden = NO;
    self.btnAfresh.hidden = YES;
    self.btnEnsure.hidden = YES;
    self.btnBack.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self.btnAfresh.centerX = kScreenWidth * 0.5;
        self.btnEnsure.centerX = kScreenWidth * 0.5;
    }];
}

#pragma mark - tapGesture
-(void)tapScreen:(UITapGestureRecognizer *)tapGesture
{
    CGPoint point = [tapGesture locationInView:self.view];
    [self.recorder setFocusCursorWithPoint:point];
    [self setFocusCursorWithPoint:point];
}

#pragma mark - NSNotificationCenter
//监听刚进入后台 推荐如果正在录制则停止 如果未开始录制则返回上一个界面
- (void)enterBackgroundMode:(NSNotification *)noti
{
    //进入后台
    if (self.recorder.isCapturing && !self.recorder.isPaused)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self stopRecord];
        });
    }
    else
    {
        //非暂停状态 暂停状态不做任何操作
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self clickedBack:nil];
        });
    }
}


#pragma mark - ALiVideoRecordDelegate
/**
 录制的进度

 @param progress progress description
 */
- (void)recordProgress:(CGFloat)progress
{
    
}

@end
